   package com.dlz.systemshop.service;



   import com.dlz.systemshop.config.StorageProperties;
   import jakarta.annotation.PostConstruct;
   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.core.io.Resource;
   import org.springframework.core.io.UrlResource;
   import org.springframework.stereotype.Service;
   import org.springframework.util.FileSystemUtils;
   import org.springframework.web.multipart.MultipartFile;

   import java.io.IOException;
   import java.net.MalformedURLException;
   import java.nio.file.Files;
   import java.nio.file.Path;
   import java.nio.file.Paths;
   import java.util.stream.Stream;

   @Service
   public class StorageService {

       private final Path root ;

       @Autowired
       public StorageService(StorageProperties properties) {
           this.root = Paths.get(properties.getLocation());
       }
       @PostConstruct
       public void init() {
           try {
               Files.createDirectories(root);
           } catch (IOException e) {
               throw new RuntimeException("Could not initialize folder for upload!", e);
           }
       }

       public Path save(MultipartFile file) {
           try {
               Path targetLocation = this.root.resolve(file.getOriginalFilename());
               Files.copy(file.getInputStream(), targetLocation);
               return targetLocation; // 返回保存后的文件路径
           } catch (Exception e) {
               throw new RuntimeException("Could not store the file. Error: " + e.getMessage(), e);
           }
       }

       public Resource load(String filename) {
           try {
               Path file = root.resolve(filename);
               Resource resource = new UrlResource(file.toUri());

               if (resource.exists() || resource.isReadable()) {
                   return resource;
               } else {
                   throw new RuntimeException("Could not read the file!");
               }
           } catch (MalformedURLException e) {
               throw new RuntimeException("Error: " + e.getMessage(), e);
           }
       }

       public void deleteAll() {
           FileSystemUtils.deleteRecursively(root.toFile());
       }

       public Stream<Path> loadAll() {
           try {
               return Files.walk(this.root, 1)
                       .filter(path -> !path.equals(this.root))
                       .map(this.root::relativize);
           } catch (IOException e) {
               throw new RuntimeException("Failed to read stored files", e);
           }
       }

       public String getSavePath(String filename) {
           return this.root.resolve(filename).toString();
       }

       public String getRelativePath(Path path) {
           // 获取相对于根路径的相对路径
           Path relativizedPath = root.relativize(path);
           return relativizedPath.toString();
       }
   }
   